import Mock from 'mockjs'
console.log('[Mock] 家政产品模块已加载')
// 数据存取方法保持不变
const getCategories = () => JSON.parse(localStorage.getItem('mock_product_categories')) || []
const getProducts = () => JSON.parse(localStorage.getItem('mock_products')) || []
const saveCategories = (data) => localStorage.setItem('mock_product_categories', JSON.stringify(data))
const saveProducts = (data) => localStorage.setItem('mock_products', JSON.stringify(data))


/* 初始化测试数据 */
if (!localStorage.getItem('mock_product_categories')) {
  saveCategories([
    { id: 1, name: '日常保洁', icon: 'hot-o', description: '全屋深度清洁服务' },
    { id: 2, name: '衣物护理', icon: 'flower-o', description: '专业团队进行衣物护理' },
    { id: 3, name: '月嫂服务', icon: 'brush-o', description: '专业母婴护理服务' },
    { id: 4, name: '家电维修', icon: 'tv-o', description: '专业家电维修团队' }
  ])
}

if (!localStorage.getItem('mock_products')) {
  saveProducts(Mock.mock({
    'list|6-10': [{
      'id|+1': 1001,
      'name': '@ctitle(2,5)',
      'price': '@natural(80, 300)',
      'duration': '@natural(2, 8)小时',
      'categoryId|1-4': 1,
      'rating|1-5.1': 1,
      'bookCount': '@natural(50, 1000)',
      'imgUrl': Mock.Random.image('200x200', '#ff776e', '家政服务')
    }]
  }).list)
}

/* 接口模拟（全部使用字符串路径）*/
// 1. 获取所有产品类型
Mock.mock('/api/categories', 'get', () => ({
  code: 200,
  data: getCategories()
}))

// 2. 获取产品列表（带分页和过滤）
Mock.mock('/api/products', 'get', (req) => {
  const queryString = req.url.split('?')[1] || ''
  const params = Object.fromEntries(new URLSearchParams(queryString))
  
  const categoryId = params.categoryId
  const page = parseInt(params.page) || 1
  const pageSize = parseInt(params.pageSize) || 10

  // 过滤逻辑
  let filtered = getProducts()
  if (categoryId) {
    filtered = filtered.filter(p => p.categoryId == categoryId)
  }

  // 分页处理
  const start = (page - 1) * pageSize
  const end = start + pageSize
  
  return {
    code: 200,
    data: {
      list: filtered.slice(start, end),
      total: filtered.length,
      page,
      pageSize
    }
  }
})

// 通过categoryId获取产品列表
Mock.mock('/api/category/:categoryId/products','get',req=>{
  console.log(req.url);
})

// 4. 创建新产品
Mock.mock('/api/products', 'post', (req) => {
  const newProduct = JSON.parse(req.body)
  const products = getProducts()
  
  newProduct.id = Math.max(...products.map(p => p.id)) + 1
  products.push(newProduct)
  saveProducts(products)
  
  return { code: 200, data: newProduct }
})

// 5. 删除产品（使用路径参数）
Mock.mock('/api/products/:id', 'delete', (req) => {
  const { id } = req.params // 直接通过 params 获取
  const products = getProducts().filter(p => p.id != id)
  saveProducts(products)
  
  return { code: 200, message: '删除成功' }
})